package com.leetcode.partition8;

import java.util.Arrays;
import java.util.Stack;

/**
 * @author `RKC`
 * @date 2021/10/6 10:14
 */
public class LC739每日温度 {

    public static int[] dailyTemperatures(int[] temperatures) {
        return monotonicStack(temperatures);
    }

    public static void main(String[] args) {
        int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73};
        System.out.println(Arrays.toString(dailyTemperatures(temperatures)));
    }

    private static int[] monotonicStack(int[] temperatures) {
        int[] answers = new int[temperatures.length];
        //单调栈存放对应元素的下标，维护一个递减栈
        Stack<Integer> s = new Stack<>();
        s.push(0);
        for (int i = 1; i < temperatures.length; i++) {
            if (temperatures[i] > temperatures[s.peek()]) {
                //当前元素大于栈顶元素，循环pop出元素，直到栈空或者栈顶元素大于当前元素，再将当前元素push进栈
                while (!s.isEmpty() && temperatures[s.peek()] < temperatures[i]) {
                    //因为单调栈存放的是元素下标，因此可以直接计算
                    answers[s.peek()] = i - s.peek();
                    s.pop();
                }
            }
            //符合当前栈的单调性，直接入栈
            s.push(i);
        }
        return answers;
    }
}
